package com.odobenus.client.processor;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.StringUtils;

import com.odobenus.client.tools.BeanUtils;

public class AplolloBeanPostProcessor implements BeanPostProcessor {
	public static Map<String, List<Object>> hasValueMap = new HashMap<String, List<Object>>();

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		Class<?> objClz;
		if (AopUtils.isAopProxy(bean)) {
			objClz = AopUtils.getTargetClass(bean);
		} else {
			objClz = bean.getClass();
		}
		try {
			if(objClz.isAnnotationPresent(ConfigurationProperties.class)) {
				ConfigurationProperties configurationProperties = objClz.getAnnotation(ConfigurationProperties.class);
				String prefix = configurationProperties.prefix();
				for (Field field : objClz.getDeclaredFields()) {
					if (BeanUtils.isSimpleType(field)) {
						String key = prefix.concat(".").concat(field.getName());
						if (!StringUtils.isEmpty(key)) {
							if (hasValueMap.containsKey(key)) {
								hasValueMap.get(key).add(bean);
							} else {
								List<Object> beans = new ArrayList<Object>();
								beans.add(bean);
								hasValueMap.put(key,beans);
							}
						}
					}
				}
			}
			

		} catch (Exception e) {
			throw new BeanCreationException(beanName, e);
		}
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

}
